package com.hlg.xboot.core.media;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;

/**
 * @author Bashan
 */
public class VideoThumbTaker extends FFMPEGInfo {

    public VideoThumbTaker(String videoUrl) {
        super(videoUrl);
    }

    public VideoThumbTaker(String app, String videoUrl) {
        super(app, videoUrl);
    }

    public void loadThumb(String thumbFilename, int width, int height, int hour, int min, float sec)
            throws IOException, InterruptedException {
        ProcessBuilder processBuilder = new ProcessBuilder(this.app, "-y", "-i", this.videoUrl, "-vframes", "1",
                "-ss", hour + ":" + min + ":" + sec, "-f", "mjpeg", "-s", width + "*" + height, "-an", thumbFilename);
        Process process = processBuilder.start();
        InputStream stderr = process.getErrorStream();
        InputStreamReader isr = new InputStreamReader(stderr);
        BufferedReader br = new BufferedReader(isr);
        String line;
        while ((line = br.readLine()) != null) ;
        process.waitFor();
    }

    /**
     * 加载最后一帧缩略图
     * @param thumbFilename 缩略图保存地址
     * @param width     缩略图宽
     * @param height    缩略图高
     * @throws IOException
     * @throws InterruptedException
     */
    public void loadLastThumb(String thumbFilename, int width, int height)
            throws IOException, InterruptedException {
        VideoInfo videoInfo = new VideoInfo(this.videoUrl);
        videoInfo.loadVideoInfo();
        loadThumb(thumbFilename, width, height, videoInfo.getHours(),
                videoInfo.getMinutes(), videoInfo.getSeconds() - 0.2f);
    }

    /**
     * 加载第一帧缩略图
     * @param thumbFilename 缩略图保存地址
     * @param width     缩略图宽
     * @param height    缩略图高
     * @throws IOException
     * @throws InterruptedException
     */
    public void loadFirstThumb(String thumbFilename, int width, int height)
            throws IOException, InterruptedException {
        if (width <= 0) {
            width = 400;
        }
        if (height <= 0) {
            height = 400;
        }
        loadThumb(thumbFilename, width, height, 0, 0, 1);
    }
}